#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <cassert>

#define Path "./fifo"
#define Mode 0666
class Fifo
{
public:
    Fifo(const std::string& p = Path)
        :_path(p)
    {
        umask(0);
        int n = mkfifo(_path.c_str(),Mode);
        if(n == 0)
        {
            std::cout << "mkFifo success" << std::endl;
        }
        else
        {
            std::cout << "mkFifo fail"<< " "<< "errno:" << errno << "strerror:" << strerror(errno) << std::endl;
        }
    }

    ~Fifo()
    {
        int n = unlink(_path.c_str());
        if (n == 0)
        {
            std::cout << "rmFifo success" << std::endl;
        }
        else
        {
            std::cout << "rmFifo fail"<< " "<< "errno:" << errno << "strerror:" << strerror(errno) << std::endl;
        }
    }

private:
    std::string _path; // 文件路径+文件名
};


class Sync
{
public:
    Sync()
    :_rfd(-1)
    ,_wfd(-1)
    {}
    void OpenReadorDie()
    {
        _rfd = open(Path,O_RDONLY);
        if(_rfd < 0)
        {
            std::cout << "open fail"<< " "<< "errno:" << errno << "strerror:" << strerror(errno) << std::endl;
            exit(1);
        }
    }
    void OpenWriteorDie()
    {
        _wfd = open(Path,O_WRONLY);
        if(_wfd < 0)
        {
            std::cout << "open fail"<< " "<< "errno:" << errno << "strerror:" << strerror(errno) << std::endl;
            exit(2);
        }
    }


    bool Wait()
    {
        bool ret = true;
        uint32_t  c = 0;
        ssize_t n = read(_rfd,&c,sizeof(uint32_t ));
        if(n == sizeof(uint32_t ))
        {
            //读端读到了，唤醒
            std::cout<<"Sever wakeup  "<<std::endl;
        }
        else if(n == 0)
        {
            ret = false;
        }
        else
        {
            return false;
        }
        return ret;

    }
    void Wakeup()
    {
        uint32_t  c = 0;
        ssize_t n = write(_wfd,&c,sizeof(uint32_t ));
        assert(n == sizeof(uint32_t ));
        //写端写了对的
        std::cout<<"wakeup Sever "<<std::endl;
    }


private:
    int _rfd;
    int _wfd;
};

